package middleware

import (
	"h8QuestionnaireServer/components/cache"
	. "h8QuestionnaireServer/pojo/constant"
	"h8QuestionnaireServer/pojo/response"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
)
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}

func TokenAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		log.Info().Msgf("token auth uri %s, token %s", c.Request.RequestURI, token)
		if len(token) == 0 {
			c.JSON(http.StatusOK, response.GenError(response.GENERAL_ERROR, "无验证信息"))
			c.Abort()
		} else {
			var openid string
			var err error

			cacheOpenid, err := cache.GetConn(SESSION_CACHE_DB).Get(token)
			if err != nil {
				log.Error().Msgf("validate token %s error %v", token, err)
				c.JSON(http.StatusOK, response.GenError(response.GENERAL_ERROR, "Token验证失败"))
				c.Abort()
			}

			openid = cacheOpenid.(string)

			log.Info().Msgf("test openid %v", openid)
			if len(openid) > 0 {
				if err != nil {
					c.JSON(http.StatusOK, response.GenError(response.PARAM_ERROR, err.Error()))
					return
				}
				c.Set("openid", openid)
				cache.GetConn(SESSION_CACHE_DB).Expire(token, 7200)
				cache.GetConn(SESSION_CACHE_DB).Expire(openid, 7200)
			}
			c.Next()
		}
	}
}
